/*
 * @(#)DmsInvitationAjaxProcessor.java 
 * Copyright (c) 2006 DCIVision Ltd All rights reserved.
 * 
 *  This software is the confidential and proprietary information of DCIVision Ltd 
 *  ("Confidential Information"). You * shall not disclose such Confidential
 *   Information and shall use it only in accordance with the terms of the 
 *   license agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.core;

import java.sql.Connection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;

import uk.ltd.getahead.dwr.ExecutionContext;

import com.dcivision.alert.core.AlertManager;
import com.dcivision.alert.core.DocumentInvitationBean;
import com.dcivision.alert.core.DocumentInvitationManager;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.user.bean.UserGroup;
import com.dcivision.user.bean.UserRecord;
import com.dcivision.user.bean.UserRole;

/**
 * <p>
 * Class Name: DmsInvitationAjaxProcessor
 * Function : this class relation with jsp page
 * pass DWR library get data. 
 * </p>
 * 
 * @author barbin tao
 * @company DCIVision Limited
 * @creation date 2006-11-27
 */
public class DmsInvitationAjaxProcessor {


  public DocumentInvitationManager m_DocumentInvitationManager;
  public DocumentInvitationBean invitationBean;
  protected Log log = new LogFactoryImpl().getInstance(this.getClass());  
  private SessionContainer sessionContainer;
  private Connection conn;
  private HttpServletRequest request;
  private static String FLAG="|";
  
  /*************
   * default constructor
   *
   */
  public DmsInvitationAjaxProcessor (){

  }

  /**************************************************
   * function : change document invitation 
   * @param alertID
   * @param docID
   * @param date
   * @return
   */
  public boolean updateDueDate(String alertID,String docID,String date){
	try{
		request = ExecutionContext.get().getHttpServletRequest();
	  	sessionContainer = getSessionContainer(request);
	  	conn = getDBConnection();
	  	m_DocumentInvitationManager = new DocumentInvitationManager(sessionContainer,conn);
	  	m_DocumentInvitationManager.updateDueDate(TextUtility.parseIntegerObj(alertID),date);
	  	this.release();
		return true;
	}catch(Exception e){
		return false;	
	}
    
  }
  
  /***************************************************
   * fucntion: cancel document invitation
   * @param alertID
   * @param docID
   * @param date
   * @return
   */

  public boolean cancelInvitation(String alertID,String docID,String date){
    try{
    	request = ExecutionContext.get().getHttpServletRequest();
      	sessionContainer = getSessionContainer(request);
      	conn = getDBConnection();
      	m_DocumentInvitationManager = new DocumentInvitationManager(sessionContainer,conn);
      	m_DocumentInvitationManager.cancelInvitation(TextUtility.parseIntegerObj(alertID));
      	this.release();
 	  	return true;
	}catch(Exception e){
		return false;	
	}
  }

  /*******************************************************
   * function quick invitation for document invite to send
   * @param docID
   * @param userList
   * @param groupList
   * @param roleList
   * @return
   */
  public boolean quickInvitation(String docID,String[] userList,String[] groupList,String[] roleList){
    try{
    	request = ExecutionContext.get().getHttpServletRequest();
      	sessionContainer = getSessionContainer(request);
      	conn = getDBConnection();
      	m_DocumentInvitationManager = new DocumentInvitationManager(sessionContainer,conn);
      	//m_DocumentInvitationManager.createInvitation();
      	this.release();
 	  	return true;
	}catch(Exception e){
		return false;	
	}  
  }
  
  /*****************************
   * 
   * @return
   */
  public String getInvitationByUpdatAlertID(){
	request = ExecutionContext.get().getHttpServletRequest();
	sessionContainer = getSessionContainer(request);
	conn = getDBConnection();
	m_DocumentInvitationManager = new DocumentInvitationManager(sessionContainer,conn);
    return "";
  }

  /*****************************************
   * get all a document invitation .
   * @param docID
   * @param curPage
   * @param sortAttribute
   * @param sortOrder
   * @return
   */
  public List getAllInvitationList(String docID,String curPage,String sortAttribute,String sortOrder){
    request = ExecutionContext.get().getHttpServletRequest();
	sessionContainer = getSessionContainer(request);
	conn = getDBConnection();
	m_DocumentInvitationManager = new DocumentInvitationManager(sessionContainer,conn);
	List allInvitation = new ArrayList();
	List data = new ArrayList();
	try{
		allInvitation = m_DocumentInvitationManager.getAllInvitationList(docID,sessionContainer.getUserRecordID(),TextUtility.parseInteger(curPage),sortAttribute,sortOrder);
	}catch(Exception e){
		return null;
	}
	
	AlertManager alertManager = new AlertManager(sessionContainer,conn);
	
	for(int i=0; i<allInvitation.size(); i++){
		DocumentInvitationBean inviteBean = (DocumentInvitationBean)allInvitation.get(i);
		List userList = inviteBean.getUser();
		StringBuffer useSb = new StringBuffer();
		for(int j=0; j<userList.size(); j++){
			UserRecord user = (UserRecord)userList.get(j);
			useSb.append("U:"+user.getFullName());
			if( inviteBean.getReadUser().contains(user.getFullName()) ) {
			  useSb.append(":1;");
			}else {
			  useSb.append(":2;");
			}
		}
		
		List groupList = inviteBean.getGroup();
		for(int j=0; j<groupList.size(); j++){
			UserGroup group = (UserGroup)groupList.get(j);
			useSb.append("G:"+group.getGroupName());
			try {
        List ids = alertManager.getDistinctUserIDListByLists(null, new String[] {group.getID().toString()}, null);
        for(int n = 0 ; n < ids.size() ; n ++ ) {
          String userName = UserInfoFactory.getUserFullName((Integer)ids.get(n));
          useSb.append(":" + userName);
          if( inviteBean.getReadUser().contains(userName) ) {
            useSb.append(":1");
          }else {
            useSb.append(":2");
          }
        }
      } catch (ApplicationException exp) {
        log.error(exp);
      }
      useSb.append(";");
		}
		
		List roleList = inviteBean.getRole();
		for(int j=0; j<roleList.size(); j++){
			UserRole role = (UserRole)roleList.get(j);
			useSb.append("R:"+role.getRoleName());
			try {
        List ids = alertManager.getDistinctUserIDListByLists(null, null, new String[] {role.getID().toString()});
        for(int n = 0 ; n < ids.size() ; n ++ ) {
          String userName = UserInfoFactory.getUserFullName((Integer)ids.get(n));
          useSb.append(":" + userName);
          if( inviteBean.getReadUser().contains(userName) ) {
            useSb.append(":1");
          }else {
            useSb.append(":2");
          }
        }
      } catch (ApplicationException exp) {
        log.error(exp);
      }
			useSb.append(";");
		}
		
		List externalList = inviteBean.getExternalEmail();

		for(int j=0; j<externalList.size(); j++){
			String email = (String )externalList.get(j);
			useSb.append("E:"+email+";");
		}
		
		List readUserList = inviteBean.getReadUser();
		StringBuffer readSb = new StringBuffer();
		for(int j=0; j<readUserList.size(); j++){
			String user = (String)readUserList.get(j);
			readSb.append(user).append(";");
		}
		List unReadUserlist = inviteBean.getUnReadUser();
		StringBuffer unreadSb = new StringBuffer();
		for(int j=0; j<unReadUserlist.size(); j++){
			String  user = (String)unReadUserlist.get(j);
			unreadSb.append(user).append(";");
		}
		Integer allUser = new Integer(inviteBean.getReadUser().size()+inviteBean.getUnReadUser().size());
		Integer readUser = new Integer(inviteBean.getReadUser().size());
		String message = inviteBean.getMessage();
		
		String oriMessage = message;
		if(!Utility.isEmpty(message)){
			oriMessage = oriMessage.replaceAll("\"","");
			oriMessage = oriMessage.replaceAll("\n","<BR>");
			oriMessage = oriMessage.replaceAll("\r",""); 
			oriMessage = TextUtility.htmlEncode(oriMessage);
			oriMessage = TextUtility.escapeJSString(oriMessage);
			if(!Utility.isEmpty(message) && message.length()>30){
				message = message.substring(0,30)+"...";
			}
			message = message.replaceAll("\"","");
			message = message.replaceAll("\n","");
			message = message.replaceAll("\r","");
			message = TextUtility.htmlEncode(message);
			message = TextUtility.escapeJSString(message);
		}
		String subject = inviteBean.getSubject();		
		String oriSubject = inviteBean.getSubject();
		if(!Utility.isEmpty(subject)){
			oriSubject = oriSubject.replaceAll("\"","");
			//oriSubject = TextUtility.htmlEncode(subject);
			oriSubject = TextUtility.escapeJSString(oriSubject);
			if(!Utility.isEmpty(subject) && subject.length()>60){
				subject = subject.substring(0,60)+"...";
			}
			subject = subject.replaceAll("\"","");
			//subject = TextUtility.htmlEncode(subject);
			//subject = TextUtility.escapeJSString(subject);
		}
		StringBuffer sb = new StringBuffer();
		String format = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DATE_FORMAT) + " HH:mm:ss";
		DateFormat dateFormat = new SimpleDateFormat(format);
		sb.append(inviteBean.getRecordCount()).append(FLAG) // record count 0
		.append(dateFormat.format(inviteBean.getDate())).append(FLAG) // create date 1
		.append(Utility.isEmpty(inviteBean.getSubject())?"null":subject).append(FLAG) // subject 2
		.append(Utility.isEmpty(inviteBean.getMessage())?"null":message).append(FLAG) // message 3
		.append(Utility.isEmpty(allUser)?"null":allUser.toString()).append(FLAG)// all read 4
		.append(Utility.isEmpty(readUser)?"null":readUser.toString()).append(FLAG) // read 5
		.append(Utility.isEmpty(inviteBean.getDueDate())?"null":TextUtility.formatTimestampToDate(inviteBean.getDueDate())).append(FLAG) // due date 6
		.append(inviteBean.getStatus()).append(FLAG) // status 7
		.append(inviteBean.getUpdateAlertTypeID()).append(FLAG) // alert Type id 8
		.append(sortAttribute).append(FLAG) // sortAttribute 9
		.append(sortOrder).append(FLAG) // sortOrder 10
		.append(Utility.isEmpty(useSb.toString())?"null":useSb.toString()).append(FLAG)// invtee 11
		.append(Utility.isEmpty(readSb.toString())?"null":readSb.toString()).append(FLAG) // read  12
		.append(Utility.isEmpty(unreadSb.toString())?"null":unreadSb.toString()).append(FLAG) // unread 13
		.append(Utility.isEmpty(inviteBean.getSubject())?"null":oriSubject).append(FLAG)//14 oriSubject
		.append(Utility.isEmpty(inviteBean.getMessage())?"null":oriMessage).append(FLAG);//15 orimessage
		data.add(sb.toString());
	}	
    return data;
  }
  /**********************
   * get sessionContainer
   * @param request
   * @return
   */
  private SessionContainer getSessionContainer(HttpServletRequest request) {
    SessionContainer ctx = (SessionContainer)request.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    if (ctx==null) {
      ctx = new SessionContainer();
      request.getSession().setAttribute(GlobalConstant.SESSION_CONTAINER_KEY, ctx);
    }
    return(ctx);
  }
  

  /*********************
   * get Database connection
   * @return
   */
  private Connection getDBConnection(){
  	if(this.conn!=null){
  		return conn;
  	}else{
  		try{
  			conn=DataSourceFactory.getConnection();
  		}catch(Exception e){
  			log.error("get Connection error!");
  		}
  		return conn;
  	}
  }
  
  public synchronized void release() {
	    this.sessionContainer = null;
	    this.conn = null;
	  }
	  
}
